<?php
error_reporting(E_ALL);
ini_set('display_errors','On');

if ($_SERVER['REQUEST_METHOD'] == 'POST' or true)
{
	/*$_POST['h'] = 100;
	$_POST['w'] = 417;
	$_POST['x'] = 18;
	$_POST['y'] = 66;
    $file = "../../pessoa/imagens/fotos/4e1d92ee1b35b.jpg";*/
	$file = '../../'.$_POST['fileName'];
    
	$info = pathinfo($file);
	$newFileName = basename($file,'.'.$info['extension']).'_t';
	$newFilePath = '../imagens/fotos/' . $newFileName;

	
	while(file_exists($newFilePath.'.'.$info['extension']))
	{
		$newFileName.= rand(0,9);
		$newFilePath = '../imagens/fotos/' . $newFileName;
	}
	if(file_exists($file))
	{
		list($width, $height, $image_type) = getimagesize($file);
		
		switch ($image_type)
	    {
	        case 1: $src = imagecreatefromgif($file); break;
	        case 2: $src = imagecreatefromjpeg($file);  break;
	        case 3: $src = imagecreatefrompng($file); break;
	        default: return '';  break;
	    }

        
	    $tmp = imagecreatetruecolor($_POST['w'], $_POST['h']);
		if(($image_type == 1) OR ($image_type==3))
	    {
	        imagealphablending($tmp, false);
	        imagesavealpha($tmp,true);
	        $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
	        imagefilledrectangle($tmp, 0, 0, $_POST['w'],$_POST['h'], $transparent);
	    }
		
		ob_start();
		imagecopy($tmp, $src, 0, 0, $_POST['x'],$_POST['y'], $_POST['w'], $_POST['h']);
		
		switch ($image_type)
	    {
	        case 1: imagegif($tmp); break;
	        case 2: imagejpeg($tmp, NULL, 100);  break; // best quality
	        case 3: imagepng($tmp, NULL, 0); break; // no compression
	        default: echo ''; break;
	    }
		
	    $final_image = ob_get_contents();
		ob_end_clean();
		$fp = fopen($newFilePath.'.'.$info['extension'],'w');
	    fwrite ($fp, $final_image);
	    fclose ($fp);
	    echo $newFileName.'.'.$info['extension'];
		exit;
	}
}
?>
